package com.itcast.rpc.client.proxy;

import com.itcast.common.annotation.RpcClient;
import com.itcast.common.utils.SpringBeanFactory;
import com.itcast.rpc.client.config.RpcClientConfiguration;
import org.apache.commons.collections.CollectionUtils;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 动态代理扫描管理器
 */
@Component
public class ServiceProxyManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceProxyManager.class);

    /**
     * RpcClient 客户端信息配置
     */
    @Autowired
    private RpcClientConfiguration configuration;

    /**
     * 动态代理拦截处理器
     */
    @Autowired
    private ProxyHelper proxyHelper;

    /**
     * 初始化代理实现
     */
    public void initServiceProxyInstance() {

        // 1. 扫描@RpcClient对应的包
        Reflections reflections = new Reflections(configuration.getRpcClientApiPackage());
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(RpcClient.class);
        if (CollectionUtils.isNotEmpty(typesAnnotatedWith)){
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) SpringBeanFactory.context().getAutowireCapableBeanFactory();
            for (Class<?> cls : typesAnnotatedWith) {
                String serviceName = cls.getName();
                Object instance = proxyHelper.newProxyInstance(cls);
                beanFactory.registerSingleton(serviceName,instance);
            }
        }
    }
}
